package com.example.server.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.sysuser.SysUser;
import com.example.domain.sysuser.dto.SysUserSaveDTO;
import com.example.mapper.sysuser.SysUserMapper;
import com.example.mybatis.MyMetaObjectHandler;
import com.example.redis.service.RedisService;
import com.example.security.exception.ServiceImplException;
import com.example.security.service.TokenService;
import com.example.server.sysuser.ISysUserServer;
import com.example.utils.BCryptUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.HttpConstants;
import oj.common.core.domain.LoginUser;
import oj.common.core.domain.Result;
import oj.common.core.enums.ResultCode;
import oj.common.core.enums.UserIdentity;
import oj.common.core.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SysUserServerImpl implements ISysUserServer {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private MyMetaObjectHandler metaObjectHandler;
    @Qualifier("redisService")
    @Autowired
    private RedisService redisService;

    /**
     * 对于这里的返回值，消息和状态码想到用枚举类来进行实现，统一结果返回使用Result来进行返回
     * @param userAccount
     * @param password
     * @return
     */
    @Override
    public Result selectUserByAccount(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select * from sys_user_db  where user_account=#{userAccount};
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getPassword,SysUser::getUserId,SysUser::getNickName,SysUser::getUserAccount)
                .eq(SysUser::getUserAccount, userAccount));
        if(sysUser == null){
            return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //这里都不能进行这样比较
        if(BCryptUtils.matchesPassword(password, sysUser.getPassword())){
            //针对身份认证的时候这里就需要进行传输数据了
            //传输的数据有，这个id  身份认证，生成token的密钥
            return Result.success(tokenService.createToken(sysUser.getUserId(), UserIdentity.ADMIN.getValue(),secret,sysUser.getNickName(),null ));
        }
        return Result.failed(ResultCode.FAILED_LOGIN);
    }

    @Override
    public int addSysUser(SysUserSaveDTO sysUserSaveDTO) {
        //先进行构造对象
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        List<SysUser> userList = sysUserMapper.selectList(queryWrapper.eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if(CollectionUtil.isNotEmpty(userList)){
            //这里应该自定义一个异常
            throw new ServiceImplException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        //密码要进行一个加密
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return  sysUserMapper.insert(sysUser);
    }

    @Override
    public LoginUser getUserNickName(String token) {
        //1.先对token进行解析，然后再去调用redis，反序列化拿到数据返回给前端。
        //2.将解析token的方法封装在tokenService类中。
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.getLoginUser(token, secret);
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        //拿到token之后开始解析
        Claims claims = JwtUtils.parseToken(token, secret);
        String userKey=tokenService.getUserKey(claims);
        if(userKey==null) {
            return false;
        }
        String tokenKey= tokenService.getTokenKey(userKey);
        return redisService.deleteObject(tokenKey);
    }
}
